// 游戏列表状态管理
let gamesState = {
    games: [],
    filters: {
        type: 'all',
        platform: 'all',
        year: 'all',
        rating: 'all'
    },
    pagination: {
        currentPage: 1,
        totalPages: 1,
        pageSize: 12
    }
};

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 初始化筛选器事件监听
    initFilterListeners();
    // 初始化搜索功能
    initSearch();
    // 初始化分页
    initPagination();
    // 初始化测评表单
    initReviewForm();
    // 加载游戏数据
    loadGames();
});

// 初始化筛选器事件监听
function initFilterListeners() {
    const filterSelects = document.querySelectorAll('.filter-group select');
    filterSelects.forEach(select => {
        select.addEventListener('change', () => {
            gamesState.filters[select.id] = select.value;
            gamesState.pagination.currentPage = 1;
            loadGames();
        });
    });
}

// 初始化搜索功能
function initSearch() {
    const searchInput = document.querySelector('.search-box input');
    const searchButton = document.querySelector('.search-box button');

    let debounceTimer;
    searchInput.addEventListener('input', (e) => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            performSearch(e.target.value);
        }, 500);
    });

    searchButton.addEventListener('click', () => {
        performSearch(searchInput.value);
    });
}

// 执行搜索
function performSearch(query) {
    gamesState.filters.search = query;
    gamesState.pagination.currentPage = 1;
    loadGames();
}

// 加载游戏数据
async function loadGames() {
    try {
        // 构建API请求参数
        const params = new URLSearchParams({
            page: gamesState.pagination.currentPage,
            pageSize: gamesState.pagination.pageSize,
            type: gamesState.filters.type,
            platform: gamesState.filters.platform,
            year: gamesState.filters.year,
            rating: gamesState.filters.rating,
            search: gamesState.filters.search || ''
        });

        // API调用示例
        // const response = await fetch(`/api/games?${params}`);
        // const data = await response.json();
        
        // 模拟API响应数据
        const data = {
            games: [
                {
                    id: 1,
                    title: "赛博朋克 2077",
                    cover: "https://via.placeholder.com/300x200",
                    rating: 9.5,
                    platforms: ["windows", "playstation", "xbox"],
                    genres: ["开放世界", "角色扮演"],
                    releaseDate: "2020",
                    publisher: "CD Projekt Red"
                }
                // ... 更多游戏数据
            ],
            totalPages: 10
        };

        // 更新状态
        gamesState.games = data.games;
        gamesState.pagination.totalPages = data.totalPages;

        // 渲染游戏列表
        renderGames();
        // 更新分页
        updatePagination();

    } catch (error) {
        console.error('加载游戏数据失败:', error);
        // 显示错误提示
        showError('加载游戏数据失败，请稍后重试');
    }
}

// 渲染游戏列表
function renderGames() {
    const gamesGrid = document.querySelector('.games-grid');
    gamesGrid.innerHTML = gamesState.games.map(game => createGameCard(game)).join('');
}

// 创建游戏卡片HTML
function createGameCard(game) {
    const platformIcons = {
        windows: 'fa-windows',
        playstation: 'fa-playstation',
        xbox: 'fa-xbox',
        switch: 'fa-gamepad'
    };

    return `
        <div class="game-card" data-game-id="${game.id}">
            <div class="card-image">
                <img src="${game.cover}" alt="${game.title}">
                <div class="card-overlay">
                    <div class="rating">
                        <span class="score">${game.rating}</span>
                        <div class="stars">${generateStars(game.rating)}</div>
                    </div>
                    <div class="card-actions">
                        <button class="view-details" onclick="showGameDetails(${game.id})">查看详情</button>
                        <button class="write-review" onclick="showReviewForm(${game.id})">写测评</button>
                    </div>
                </div>
            </div>
            <div class="card-content">
                <div class="platforms">
                    ${game.platforms.map(p => `<i class="fab ${platformIcons[p]}"></i>`).join('')}
                </div>
                <h3>${game.title}</h3>
                <p class="genre">${game.genres.join(' · ')}</p>
                <div class="meta">
                    <span class="release-date">${game.releaseDate}</span>
                    <span class="publisher">${game.publisher}</span>
                </div>
            </div>
        </div>
    `;
}

// 生成星级评分HTML
function generateStars(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    let stars = '';
    // 使用 Font Awesome 图标
    for (let i = 0; i < 5; i++) {
        if (i < fullStars) {
            stars += '<i class="fas fa-star"></i>';
        } else if (i === fullStars && hasHalfStar) {
            stars += '<i class="fas fa-star-half-alt"></i>';
        } else {
            stars += '<i class="far fa-star"></i>';
        }
    }
    return stars;
}

// 显示游戏详情
function showGameDetails(gameId) {
    // 这里可以跳转到详情页或打开详情模态框
    console.log('显示游戏详情:', gameId);
}

// 显示写测评表单
function showReviewForm(gameId) {
    const modal = document.getElementById('reviewModal');
    modal.style.display = 'flex';
    
    if (gameId) {
        const gameSelect = document.getElementById('gameSelect');
        gameSelect.value = gameId;
        gameSelect.disabled = true;
    }
    // 重置表单状态
    resetReviewForm();
}

// 重置测评表单
function resetReviewForm() {
    // 重置评分
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach(star => {
        star.classList.remove('fas');
        star.classList.add('far');
    });
    
    // 重置文本
    const textarea = document.querySelector('.review-form textarea');
    if (textarea) {
        textarea.value = '';
        updateWordCount(textarea);
    }
    
    // 重置评分文本
    const ratingText = document.querySelector('.rating-text');
    if (ratingText) {
        ratingText.textContent = '请选择评分';
    }
}

// 隐藏写测评表单
function hideReviewForm() {
    const modal = document.getElementById('reviewModal');
    modal.style.display = 'none';
    
    // 重置表单
    const gameSelect = document.getElementById('gameSelect');
    if (gameSelect) {
        gameSelect.value = '';
        gameSelect.disabled = false;
    }
    
    // 使用重置函数
    resetReviewForm();
}

// 更新字数统计
function updateWordCount(textarea) {
    const wordCount = document.querySelector('.word-count');
    const length = textarea.value.length;
    wordCount.textContent = `${length}/1000`;
    
    if (length < 100) {
        wordCount.style.color = '#ff4444';
    } else {
        wordCount.style.color = '#666';
    }
}

// 更新评分文本
function updateRatingText(rating) {
    const ratingText = document.querySelector('.rating-text');
    const texts = ['很差', '较差', '一般', '不错', '很棒'];
    ratingText.textContent = texts[rating - 1] || '请选择评分';
}

// 初始化测评表单
function initReviewForm() {
    // 检查元素是否存在
    const form = document.querySelector('.review-form');
    if (!form) return;
    
    const textarea = document.querySelector('.review-form textarea');
    if (textarea) {
        textarea.addEventListener('input', () => updateWordCount(textarea));
    }
    
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach(star => {
        star.addEventListener('click', () => {
            const rating = star.dataset.rating;
            updateStars(rating);
            updateRatingText(rating);
        });
        
        star.addEventListener('mouseover', () => {
            const rating = star.dataset.rating;
            previewStars(rating);
        });
        
        star.addEventListener('mouseout', () => {
            const currentRating = document.querySelector('.rating-input .fas')?.dataset.rating;
            previewStars(currentRating || 0);
        });
    });
}

// 预览星星效果
function previewStars(rating) {
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach((star, index) => {
        if (index < rating) {
            star.classList.remove('far');
            star.classList.add('fas');
        } else {
            star.classList.remove('fas');
            star.classList.add('far');
        }
    });
}

// 更新星星示
function updateStars(rating) {
    previewStars(rating);
}

// 初始化分页
function initPagination() {
    const pagination = document.querySelector('.pagination');
    pagination.addEventListener('click', (e) => {
        if (e.target.matches('button')) {
            const page = e.target.dataset.page;
            if (page) {
                gamesState.pagination.currentPage = parseInt(page);
                loadGames();
            }
        }
    });
}

// 更新分页UI
function updatePagination() {
    const { currentPage, totalPages } = gamesState.pagination;
    const pagination = document.querySelector('.pagination .page-numbers');
    
    let pages = [];
    if (totalPages <= 5) {
        pages = Array.from({ length: totalPages }, (_, i) => i + 1);
    } else {
        if (currentPage <= 3) {
            pages = [1, 2, 3, 4, '...', totalPages];
        } else if (currentPage >= totalPages - 2) {
            pages = [1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
        } else {
            pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
        }
    }

    pagination.innerHTML = pages.map(page => {
        if (page === '...') {
            return '<span>...</span>';
        }
        return `
            <button class="${page === currentPage ? 'active' : ''}" 
                    data-page="${page}">${page}</button>
        `;
    }).join('');
}

// 显示错误提示
function showError(message) {
    // 实现错误提示UI
    console.error(message);
} 